package jnpf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PDFCtrl;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.base.util.OptimizeUtil;
import jnpf.base.vo.*;
import jnpf.engine.model.flowengine.FlowModel;
import jnpf.engine.service.FlowDynamicService;
import jnpf.entity.DocumentVersionEntity;
import jnpf.exception.WorkFlowException;
import jnpf.service.DocumentVersionService;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.model.MergeChunkDto;
import jnpf.permission.entity.UserEntity;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.controller.SuperController;
import jnpf.entity.DocumentEntity;
import jnpf.entity.DocumentShareEntity;
import jnpf.exception.DataException;
import jnpf.model.document.*;
import jnpf.permission.service.UserService;
import jnpf.service.DocumentService;
import jnpf.util.*;
import jnpf.util.JsonUtil;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
import lombok.Cleanup;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
/**
 * 文档管理
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @date 2019年9月26日 上午9:18
 */
@Tag(name = "知识管理", description = "Document")
@RestController
@RequestMapping("/api/extend/Document")
public class DocumentController extends SuperController<DocumentService, DocumentEntity> {


    @Value("${config.file-storage.base-path:}")
    private String basePath;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DocumentService documentService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DocumentVersionService documentVersionService;
    @Autowired
    private FlowDynamicService flowDynamicService;

    /**
     * 列表
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "列表")
    @GetMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<DocumentInfoVO> info(@PathVariable("id") String id) throws DataException {
        DocumentEntity entity = documentService.getInfo(id);
        DocumentInfoVO vo = JsonUtil.getJsonToBean(entity, DocumentInfoVO.class);
        //截取后缀
        String[] fullName = vo.getFullName().split("\\.");
        if (fullName.length > 1) {
            String fullNames = "";
            for (int i = 0; i < fullName.length - 1; i++) {
                if (i > 0) {
                    fullNames += "." + fullName[i];
                } else {
                    fullNames += fullName[i];
                }
            }
            vo.setFullName(fullNames);
        }
        return ActionResult.success(vo);
    }

    /**
     * 列表
     *
     * @param docid 主键
     * @return
     */
    @Operation(summary = "列表")
    @GetMapping("/getspinfo/{docid}")
    @Parameters({@Parameter(name = "docid", description = "主键", required = true)})
    public ActionResult<DocumentEntity> getspinfo(@PathVariable("docid") String docid) throws DataException {
        DocumentEntity entity = documentService.getInfo(docid);
        QueryWrapper<DocumentVersionEntity> docver = new QueryWrapper<>();
        docver.lambda().eq(DocumentVersionEntity::getDocid,docid);
        docver.lambda().eq(DocumentVersionEntity::getVersion,entity.getVersion());
        List<DocumentVersionEntity> docverList = this.documentVersionService.list(docver);
        DocumentVersionEntity versionEntity = docverList.get(0);
        UserEntity user = this.userService.getById(entity.getCreatorUserId());
//        DocumentInfoVO vo = JsonUtil.getJsonToBean(entity, DocumentInfoVO.class);
        //截取后缀
        String[] fullName = entity.getFullName().split("\\.");
        if (fullName.length > 1) {
            String fullNames = "";
            for (int i = 0; i < fullName.length - 1; i++) {
                if (i > 0) {
                    fullNames += "." + fullName[i];
                } else {
                    fullNames += fullName[i];
                }
            }
            entity.setFilePath(entity.getFullName());
            entity.setFullName(fullNames);
            entity.setVid(versionEntity.getId());
            entity.setCreatorUserId(user.getRealName());
        }
        return ActionResult.success(entity);
    }

    /**
     * 新建
     *
     * @param documentCrForm 新建模型
     * @return
     */
    @Operation(summary = "新建")
    @PostMapping
    @Parameters({
            @Parameter(name = "documentCrForm", description = "知识模型", required = true),
    })
    public ActionResult create(@RequestBody @Valid DocumentCrForm documentCrForm) {
        DocumentEntity entity = JsonUtil.getJsonToBean(documentCrForm, DocumentEntity.class);
        if (documentService.isExistByFullName(documentCrForm.getFullName(), entity.getId(), documentCrForm.getParentId())) {
            return ActionResult.fail("文件夹名称不能重复");
        }
        entity.setEnabledMark(1);
        documentService.create(entity);
        return ActionResult.success("新建成功");
    }



    /**
     * 修改
     *
     * @param id             主键
     * @param documentUpForm 修改模型
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "documentUpForm", description = "知识模型", required = true),
    })
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid DocumentUpForm documentUpForm) {
        DocumentEntity info = documentService.getInfo(id);
        if(documentUpForm.getFullName().contains("."+info.getFileExtension())){//审批流回调修改不予处理
            return ActionResult.success("更新成功");
        } else {//重命名操作
            DocumentEntity entity = JsonUtil.getJsonToBean(documentUpForm, DocumentEntity.class);
            if (documentService.isExistByFullName(documentUpForm.getFullName(), id, documentUpForm.getParentId())) {
                return ActionResult.fail("文件夹名称不能重复");
            }
            //获取后缀名
            String[] fullName = info.getFullName().split("\\.");
            if (fullName.length > 1) {
                entity.setFullName(entity.getFullName() + "." + fullName[fullName.length - 1]);
            }
            boolean flag = documentService.update(id, entity);
            if (flag == false) {
                return ActionResult.fail("更新失败，数据不存在");
            }
        }
        return ActionResult.success("更新成功");
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "删除")
    @PostMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult delete(@PathVariable("id") String id) {
        DocumentEntity entity = documentService.getInfo(id);
        if (entity != null) {
            List<DocumentEntity> allList = documentService.getAllList(entity.getId());
            if (allList.size() > 0) {
                return ActionResult.fail("删除失败，该文件夹存在数据");
            }
            documentService.delete(entity);
            return ActionResult.success("删除成功");
        }
        return ActionResult.fail("删除失败，数据不存在");
    }

    /**
     * 列表移动到
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取知识管理列表（文件夹树）")
    @GetMapping("/FolderTree/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<ListVO<DocumentFolderTreeVO>> folderTree(@PathVariable("id") String id) {
        List<DocumentEntity> data = documentService.getFolderList();
        if (!"0".equals(id)) {
            data.remove(documentService.getInfo(id));
        }
        List<DocumentFolderTreeModel> treeList = new ArrayList<>();
        DocumentFolderTreeModel model = new DocumentFolderTreeModel();
        model.setId("-1");
        model.setFullName("全部文档");
        model.setParentId("0");
        model.setIcon("0");
        treeList.add(model);
        for (DocumentEntity entity : data) {
            DocumentFolderTreeModel treeModel = new DocumentFolderTreeModel();
            treeModel.setId(entity.getId());
            treeModel.setFullName(entity.getFullName());
            treeModel.setParentId(entity.getParentId());
            treeModel.setIcon("fa fa-folder");
            treeList.add(treeModel);
        }
        List<SumTree<DocumentFolderTreeModel>> trees = TreeDotUtils.convertListToTreeDotFilter(treeList);
        List<DocumentFolderTreeVO> listVO = JsonUtil.getJsonToList(trees, DocumentFolderTreeVO.class);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 列表（全部文档）
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "获取知识管理列表（全部文档）")
    @GetMapping
    public ActionResult<PageListVO<DocumentListVO>> allList(PageDocument page) {
        String tab = page.getActiveTab();
        page.setStartSize((page.getCurrentPage()-1)*page.getPageSize());
        List<DocumentEntity> data = new ArrayList<>();
        Integer total = 0;

        if("myWord".equals(tab)){
            data = documentService.getDocList(page);
            total = documentService.getListTotal(page);
        }
        if("0".equals(page.getParentId())){
            page.setParentId(null);
        }
        //我共享的
        if("mysharePanel".equals(tab)){
            page.setCreatorUserId(userProvider.get().getUserId());
            data = documentService.getShareOutList(page);
            total = documentService.getShareOutListCount(page);
        }
        //星标文件
        if("startPanel".equals(tab)){
            page.setIsAsterisk("1");//星标文件
            data =  documentService.getDocList(page);
            total = documentService.getListTotal(page);
        }
        //已完结文件
        if("finshedPanel".equals(tab)){
            page.setIsEnd("1");//已完结文件
            data = documentService.getDocList(page);
            total = documentService.getListTotal(page);
        }
        //资源包
        if("zybPanel".equals(tab)){
            data = documentService.getDocList(page);
            total = documentService.getListTotal(page);
        }
        //他人共享
        if("otherSharPanel".equals(tab)){
            page.setShareUserId(userProvider.get().getUserId());
            data = documentService.getShareOutList(page);
            total = documentService.getShareOutListCount(page);
        }
        //读取允许文件预览类型
        List<DocumentListVO> list = new ArrayList<>();
        String allowPreviewType = configValueUtil.getAllowPreviewFileType();
        String[] fileType = allowPreviewType.split(",");
        for (DocumentEntity documentEntity : data) {
            DocumentListVO documentListVO = new DocumentListVO();
            BeanUtils.copyProperties(documentEntity,documentListVO);
            documentListVO.setVid(documentEntity.getVid());
            documentListVO.setId(documentEntity.getId());

            //文件预览类型检验
            String s = Arrays.asList(fileType).stream().filter(type -> type.equals(documentListVO.getFileExtension())).findFirst().orElse(null);
            documentListVO.setIsPreview(s);
            //文件类型
            if(documentListVO.getType()==1){
                documentListVO.setFileTypNam(documentListVO.getFileExtension().toUpperCase()+"文件");
                //判断是否是pageoffice打开的文件
                String docTyp = documentListVO.getFileExtension().toUpperCase();
                if(docTyp.indexOf("DOC")>-1||docTyp.indexOf("XLS")>-1||docTyp.indexOf("PPT")>-1||docTyp.indexOf("PDF")>-1){
                    documentListVO.setEditable("1");
                }
            } else {
                documentListVO.setFileTypNam("文件夹");
                documentListVO.setEditable("0");
                documentListVO.setFileSize("-");
                //查询文件上传人等信息
                DocumentEntity docinfo = documentService.getInfo(documentListVO.getId());
                documentListVO.setCreatorUserId(docinfo.getCreatorUserId());
                documentListVO.setCreatorTime(docinfo.getCreatorTime());
                documentListVO.setLastModifyTime(docinfo.getLastModifyTime());
            }

            //上传人
            UserEntity user = this.userService.getById(documentListVO.getCreatorUserId());
            documentListVO.setCreatorUserId(user!=null?user.getRealName():"");
            list.add(documentListVO);
        }

        page.setTotal(total);
        PaginationVO paginationVO = JsonUtil.getJsonToBean(page, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
//        return ActionResult.success(vo);
    }

    /**
     * 列表（全部文档）采编项目内容使用
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "获取知识管理列表（全部文档）")
    @GetMapping("/allListToCompilation")
    public ActionResult<PageListVO<DocumentListVO>> allListToCompilation(PageDocument page) {
        String tab = page.getActiveTab();
        page.setStartSize((page.getCurrentPage()-1)*page.getPageSize());
        List<DocumentEntity> data = new ArrayList<>();
        Integer total = 0;
        List<String> ids = new ArrayList<>();
        if("img".equals(page.getFileType())){
            ids.add("bmp");
            ids.add("gif");
            ids.add("png");
            ids.add("jpg");
        }else if("file".equals(page.getFileType())){
            ids.add("flv");
            ids.add("mpeg");
            ids.add("mp4");
            ids.add("pdf");

        }
        data = documentService.getDocListByFileExtension(ids);
        total = documentService.getListTotalByFileExtension(ids);
        //读取允许文件预览类型
        List<DocumentListVO> list = new ArrayList<>();
        String allowPreviewType = configValueUtil.getAllowPreviewFileType();
        String[] fileType = allowPreviewType.split(",");
        for (DocumentEntity documentEntity : data) {
            DocumentListVO documentListVO = new DocumentListVO();
            BeanUtils.copyProperties(documentEntity,documentListVO);
            documentListVO.setVid(documentEntity.getVid());
            documentListVO.setId(documentEntity.getId());

            //文件预览类型检验
            String s = Arrays.asList(fileType).stream().filter(type -> type.equals(documentListVO.getFileExtension())).findFirst().orElse(null);
            documentListVO.setIsPreview(s);
            //文件类型
            if(documentListVO.getType()==1){
                documentListVO.setFileTypNam(documentListVO.getFileExtension().toUpperCase()+"文件");
                //判断是否是pageoffice打开的文件
                String docTyp = documentListVO.getFileExtension().toUpperCase();
                if(docTyp.indexOf("DOC")>-1||docTyp.indexOf("XLS")>-1||docTyp.indexOf("PPT")>-1||docTyp.indexOf("PDF")>-1){
                    documentListVO.setEditable("1");
                }
            } else {
                documentListVO.setFileTypNam("文件夹");
                documentListVO.setEditable("0");
                documentListVO.setFileSize("-");
                //查询文件上传人等信息
                DocumentEntity docinfo = documentService.getInfo(documentListVO.getId());
                documentListVO.setCreatorUserId(docinfo.getCreatorUserId());
                documentListVO.setCreatorTime(docinfo.getCreatorTime());
                documentListVO.setLastModifyTime(docinfo.getLastModifyTime());
            }

            //上传人
            UserEntity user = this.userService.getById(documentListVO.getCreatorUserId());
            documentListVO.setCreatorUserId(user!=null?user.getRealName():"");
            list.add(documentListVO);
        }

        page.setTotal(total);
        PaginationVO paginationVO = JsonUtil.getJsonToBean(page, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
//        return ActionResult.success(vo);
    }




    /**
     * 列表（共享人员）
     *
     * @param documentShareForm 文档主键
     * @return 1
     */
    @Operation(summary = "获取知识管理列表（共享人员）")
    @PostMapping("/ShareUser")
    public ActionResult<ListVO<DocumentSuserListVO>> shareUserList(@RequestBody DocumentShareForm documentShareForm) {
        List<String> docList = Arrays.asList(documentShareForm.getDocids().split(","));
        List<DocumentShareEntity> data = documentService.getShareUserList(docList);
        List<DocumentSuserListVO> list = JsonUtil.getJsonToList(data, DocumentSuserListVO.class);
        ListVO vo = new ListVO();
        vo.setList(list);
        return ActionResult.success(vo);
    }



    /**
     * 分片组装
     *
     * @param mergeChunkDto 合并模型
     * @return
     */
    @Operation(summary = "上传文件")
    @PostMapping("/merge")
    public ActionResult merge(MergeChunkDto mergeChunkDto) {
        String identifier = mergeChunkDto.getIdentifier();
        String path = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
        String filePath = XSSEscape.escapePath(path + identifier);
        String partFile = XSSEscape.escapePath(path + mergeChunkDto.getFileName());
        try {
            List<File> mergeFileList = FileUtil.getFile(new File(filePath));
            @Cleanup FileOutputStream destTempfos = new FileOutputStream(partFile, true);
            for (int i = 0; i < mergeFileList.size(); i++) {
                String chunkName = identifier.concat("-") + (i + 1);
                File files = new File(filePath, chunkName);
                if (files.exists()) {
                    FileUtils.copyFile(files, destTempfos);
                }
            }
            File partFiles = new File(partFile);
            if (partFiles.exists()) {
                MultipartFile multipartFile = FileUtil.createFileItem(partFiles);
                uploaderVO(multipartFile, mergeChunkDto.getParentId());
                FileUtil.deleteTmp(multipartFile);
            }

        } catch (Exception e) {
            System.out.println("合并分片失败:" + e);
        } finally {
            FileUtils.deleteQuietly(new File(filePath));
            FileUtils.deleteQuietly(new File(partFile));
        }
        return ActionResult.success(MsgCode.SU015.get());
    }


    /**
     * 获取下载文件链接
     *
     * @param +id 主键  vb
     * @return
     */
    @Operation(summary = "获取下载文件链接")
    @GetMapping("/Download/{vid}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public void download(@PathVariable("vid") String vid,HttpServletResponse response,HttpServletRequest request) throws IOException {
        UserInfo userInfo = userProvider.get();
        DocumentVersionEntity version = this.documentVersionService.getInfo(vid);
        DocumentEntity docinfo = this.documentService.getInfo(version.getDocid());

        File file = new File(version.getMainurl());

        if(file.exists()){
//            FileUploadUtils.downloadFile(version.getMainurl(),"514878907472713925V10.txt");

            // 获取浏览器的信息
            String agent = request.getHeader("USER-AGENT");
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                //火狐浏览器自己会对URL进行一次URL转码所以区别处理
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(docinfo.getFullName().getBytes("GB2312"), "ISO-8859-1"));
            } else if (agent.toLowerCase().indexOf("safari") > 0) {
                //苹果浏览器需要用ISO 而且文件名得用UTF-8
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(docinfo.getFullName().getBytes("UTF-8"), "ISO-8859-1"));
            } else {
                //其他的浏览器
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + java.net.URLEncoder.encode(docinfo.getFullName(), "UTF-8"));
            }

            FileInputStream fileInputStream = new FileInputStream(file);

            byte[] fileByte = new byte[(int) file.length()];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes, 0, bytes.length)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
            byteArrayOutputStream.close();
            fileByte = byteArrayOutputStream.toByteArray();

            OutputStream outputStream = null;
            outputStream = response.getOutputStream();
            outputStream.write(fileByte);
            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * 回收站（彻底删除）
     *
     * @param documentShareForm 主键
     * @return
     */
    @Operation(summary = "删除（彻底删除）")
    @PostMapping("/Trash")
    public ActionResult trashdelete(@RequestBody DocumentShareForm documentShareForm) {
        String[] docids = documentShareForm.getDocids().split(",");
        documentService.trashDelete(docids);
        return ActionResult.success("删除成功");
    }

    /**
     * 回收站（还原文件）
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "回收站（还原文件）")
    @PostMapping("/Trash/{id}/Actions/Recovery")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult trashRecovery(@PathVariable("id") String id) {
        DocumentEntity entity = documentService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("操作失败，原文件不存在");
        }
        if (!"0".equals(entity.getParentId())) {
            DocumentEntity info = documentService.getInfo(entity.getParentId());
            if (info == null) {
                return ActionResult.fail("操作失败，原文件不存在");
            }
            if (info.getEnabledMark() != null && info.getEnabledMark() == 0) {
                return ActionResult.fail("找不到父级");
            }
        }
        boolean flag = documentService.trashRecovery(id);
        if (!flag) {
            return ActionResult.fail(MsgCode.FA010.get());
        }
        return ActionResult.success(MsgCode.SU010.get());
    }

    /**
     * 分享文件
     *
     * @param documentShareForm                主键
     * @param documentShareForm 分享模型
     * @return
     */
    @Operation(summary = "分享文件/文件夹")
    @PostMapping("/Actions/Share/add")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "documentShareForm", description = "分享模型", required = true),
    })
    public ActionResult shareCreate(@RequestBody DocumentShareForm documentShareForm) {
        String[] shareUserId = documentShareForm.getUserId().split(",");
        String[] docids = documentShareForm.getDocids().split(",");
        documentService.shareCreate(docids, shareUserId);
        return ActionResult.success("操作成功");
    }

    /**
     * 共享文件（取消）
     *
     * @param documentShareForm 主键值
     * @return
     */
    @Operation(summary = "取消分享文件/文件夹")
    @PostMapping("/Actions/Share/del")
    public ActionResult shareCancel(@RequestBody DocumentShareForm documentShareForm) {
        String[] docids = documentShareForm.getDocids().split(",");
        documentService.shareCancel(docids);
        return ActionResult.success("操作成功");
    }

    @Operation(summary = "添加新标文件")
    @PostMapping("/startFile/{option}")
    @Parameters({
            @Parameter(name = "ids", description = "主键", required = true),
            @Parameter(name = "documentShareForm", description = "分享模型", required = true),
    })
    public ActionResult startFile(@PathVariable("option") String option,
                                    @RequestBody DocumentShareForm documentShareForm) {
        List<String> docids = Arrays.asList(documentShareForm.getDocids().split(","));
        for (String docid : docids) {
            DocumentEntity doc = this.documentService.getInfo(docid);
            if ("add".equals(option)) {//新增星标文件
                doc.setIsAsterisk("1");//星标文件
            }
            if ("del".equals(option)) {//取消星标文件
                doc.setIsAsterisk("0");
            }
            this.documentService.updateById(doc);
        }
        if ("add".equals(option)) {//新增星标文件
            return ActionResult.success("标记成功！");
        } else {
            return ActionResult.success("取消成功！");
        }
    }


    @Operation(summary = "文件版本列表")
    @GetMapping("/docversionList/{docid}")
    @Parameters({
            @Parameter(name = "docid", description = "主键", required = true),
    })
    public ActionResult docversionList(@PathVariable("docid") String docid) {
        QueryWrapper<DocumentVersionEntity> query = new QueryWrapper<>();
        query.lambda().eq(DocumentVersionEntity::getDocid,docid);
        query.lambda().orderByAsc(DocumentVersionEntity::getVersion);
        query.lambda().orderByDesc(DocumentVersionEntity::getLastmodifytime);
        List<DocumentVersionEntity> verlist = this.documentVersionService.list(query);
        DocumentEntity info = this.documentService.getInfo(docid);
        Map<String,String> userMap = new HashMap<String,String>();
        List<DocumentListVO> resultList = new ArrayList<>();
        for(DocumentVersionEntity ver : verlist){
            DocumentListVO vo = new DocumentListVO();
            vo.setVid(ver.getId());
            vo.setCreatorTime(ver.getCreatortime());
            vo.setLastModifyTime(info.getLastModifyTime());//完成时间
            vo.setFullName(info.getFullName());
            vo.setVersion(ver.getVersion());
            String typ = info.getFileExtension().replace(".","");
            vo.setFileType(typ.toUpperCase()+"文件");
            vo.setId(info.getId());
            if(StringUtil.isNotEmpty(info.getLastModifyUserId())) {
                UserEntity user = this.userService.getById(info.getLastModifyUserId());
                vo.setLastModifyUserId(user != null ? user.getRealName() : "");
            }
            if(info.getVersion().equals(ver.getVersion())){
                vo.setMainfetch("是");
            } else {
                vo.setMainfetch("否");
            }
            resultList.add(vo);
        }
        return ActionResult.success(resultList);
    }


    @Operation(summary = "版本升级")
    @GetMapping("/versionLv/{vid}")
    @Parameters({
            @Parameter(name = "vid", description = "版本主键", required = true),
    })
    public ActionResult versionLv(@PathVariable("vid") String vid) {
        DocumentVersionEntity verinfo = this.documentVersionService.getInfo(vid);
        DocumentEntity docinfo = this.documentService.getInfo(verinfo.getDocid());
        docinfo.setVersion(verinfo.getVersion());
        documentService.updateById(docinfo);
        verinfo.setLastmodifytime(new Date());
        documentVersionService.updateById(verinfo);
        return ActionResult.success("操作成功");
    }

    @Operation(summary = "文件版本删除")
    @GetMapping("/versiondel/{vid}")
    @Parameters({
            @Parameter(name = "vid", description = "版本主键", required = true),
    })
    public ActionResult versiondel(@PathVariable("vid") String vid) {
        DocumentVersionEntity verinfo = this.documentVersionService.getInfo(vid);
        QueryWrapper<DocumentVersionEntity> query = new QueryWrapper<>();
        query.lambda().eq(DocumentVersionEntity::getDocid,verinfo.getDocid());
        query.lambda().ne(DocumentVersionEntity::getId,vid);
        query.lambda().orderByDesc(DocumentVersionEntity::getVersion);
        List<DocumentVersionEntity> verlist = this.documentVersionService.list(query);
        if(verlist.size()==1){
            return ActionResult.fail("无法删除该版本数据!");
        }
        try{
            File file = new File(verinfo.getMainurl());
            file.delete();
        }catch (Exception e){

        }
        DocumentEntity docinfo = this.documentService.getInfo(verinfo.getDocid());
        documentVersionService.delete(verinfo);
        docinfo.setVersion(verlist.get(0).getVersion());
        documentService.updateById(docinfo);
        return ActionResult.success("删除成功");
    }

    @Operation(summary = "文件审批提交工作流")
    @GetMapping("/submitWorkFlow/{vid}")
    @Parameters({@Parameter(name = "vid", description = "主键", required = true)})
    public ActionResult submitWorkFlow(@PathVariable("vid") String vid) throws WorkFlowException {
        DocumentEntity docinfo = this.documentService.getInfo(vid);
        if(null==docinfo.getAuditsts()||docinfo.getAuditsts().equals("3")||docinfo.getAuditsts().equals("0")) {
            FlowModel flowModel = new FlowModel();
            flowModel.setFlowId("516225022965096261");
            flowModel.setStatus("0");
            flowModel.setFlowUrgent(1);
            flowModel.setTaskId(vid);
            flowModel.setId(vid);
            flowModel.setUserInfo(this.userProvider.get());
            Map<String, Object> map = new HashMap<>();
            map.put("id", vid);
            map.put("parentId", docinfo.getParentId());
            map.put("fullName", docinfo.getFullName());
            map.put("type", docinfo.getType());
            flowModel.setFormData(map);
            flowDynamicService.batchCreateOrUpdate(flowModel);
            docinfo.setAuditsts("1");//审核中
            this.documentService.updateById(docinfo);
            return ActionResult.success("操作成功");
        } else if(docinfo.getAuditsts().equals("2")){
            return ActionResult.success("审批已通过,无需重复提交审批！");
        } else {
            return ActionResult.success("流程审批中,无需重复提交！");
        }
    }


    @Operation(summary = "审核通过")
    @PostMapping("/auditWork/pass")
    public ActionResult workPass(@RequestBody DocumentShareForm documentShareForm) throws WorkFlowException {
        DocumentEntity docinfo = this.documentService.getInfo(documentShareForm.getDocids());
        docinfo.setAuditsts("2");//审核通过
        docinfo.setIsEnd("1");//完结
        docinfo.setLastModifyTime(new Date());
        docinfo.setLastModifyUserId(userProvider.get().getUserId());
        this.documentService.updateById(docinfo);
        return ActionResult.success("操作成功");
    }

    @Operation(summary = "审核不通过")
    @PostMapping("/auditWork/nopass/")
    public ActionResult worNokPass(@RequestBody DocumentShareForm documentShareForm) throws WorkFlowException {
        DocumentEntity docinfo = this.documentService.getInfo(documentShareForm.getDocids());
        docinfo.setAuditsts("3");//审核不通过
        docinfo.setIsEnd("0");
        this.documentService.updateById(docinfo);
        return ActionResult.success("操作成功");
    }

    @Operation(summary = "审核撤回")
    @PostMapping("/auditWork/chehui")
    public ActionResult chehui(@RequestBody DocumentShareForm documentShareForm) throws WorkFlowException {
        DocumentEntity docinfo = this.documentService.getInfo(documentShareForm.getDocids());
        docinfo.setAuditsts("0");//待提交审批
        docinfo.setIsEnd("0");
        this.documentService.updateById(docinfo);
        return ActionResult.success("操作成功");
    }



    /**
     * 文件/夹移动到
     *
     * @param id   主键值
     * @param toId 将要移动到Id
     * @return
     */
    @Operation(summary = "移动文件/文件夹")
    @PutMapping("/{id}/Actions/MoveTo/{toId}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "toId", description = "将要移动到Id", required = true),
    })
    public ActionResult moveTo(@PathVariable("id") String id, @PathVariable("toId") String toId) {
        if (id.equals(toId)) {
            return ActionResult.fail("不能移动到自己的文件夹");
        }
        boolean flag = documentService.moveTo(id, toId);
        if (flag == false) {
            return ActionResult.fail("更新失败，数据不存在");
        }
        return ActionResult.success("更新成功");
    }

    /**
     * 封装上传附件
     *
     * @param file
     * @param parentId
     * @return
     */
    private void uploaderVO(MultipartFile file, String parentId) {
        String fileType = UpUtil.getFileType(file);
        String baseFilePath = FileUploadUtils.getLocalBasePath()+configValueUtil.getDocumentFilePath();
        //配置文件 拼接文件路径
        String filePath = baseFilePath.replace("/",File.separator).replace("\\",File.separator);
        File f = new File(filePath);
        if(!f.exists()){
           f.mkdirs();
        }
        //假文件名
        String jianame = RandomUtil.uuId();
        //文件真是名称
        String fileName = file.getOriginalFilename();
//        List<DocumentEntity> data = documentService.getAllList(parentId);
//        String finalFileName = fileName;
//        data = data.stream().filter(t -> finalFileName.equals(t.getFullName())).collect(Collectors.toList());
//        if (data.size() > 0) {
//            fileName = DateUtil.getNow("+8") + "-" + fileName;
//        }
        String fileNamV1 = jianame + "V10"+"."+fileType;
        jianame = jianame+"."+fileType;

        //上传
//        FileInfo fileInfo = FileUploadUtils.uploadFile(file, filePath, fileName + "." + fileType);
        DocumentEntity entity = new DocumentEntity();
        entity.setType(1);//文件
        entity.setFullName(fileName);
        entity.setParentId(parentId);
        entity.setFileExtension(fileType);
        entity.setFilePath(jianame);
        entity.setFileSize(String.valueOf(file.getSize()));
        entity.setEnabledMark(1);
//        String sourcePath = UploaderUtil.uploaderImg("/api/file/Image/document/", fileInfo.getFilename());
        String scurcePath = filePath+jianame;
        entity.setUploaderUrl(scurcePath);
        //上传文件
        try{
            File vfile = new File(scurcePath);
            InputStream ins = file.getInputStream();
            //从临时文件获取临时文件刘创建正式上传文件
//            FileUtil.writeToFile(ins,filePath,jianame);
//            FileUtil.writeToFile(ins,filePath,fileNamV1);
            this.inputStreamToFile(ins,vfile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        entity.setVersion("V"+Float.parseFloat("1.0"));
        documentService.create(entity);
        String targetPath = filePath+fileNamV1;

//        String sourcePathV1 = UploaderUtil.uploaderImg("/api/file/Image/document/", fileInfoV1.getFilename());

//        String finam = entity.getFilePath().replace("."+entity.getFileExtension(),"");
//        String tarfilename = finam + "V1.0" + "." + entity.getFileExtension();
//        System.out.println(tarfilename);
//
//        String targetPath = FileUploadUtils.getLocalBasePath()+File.separator+configValueUtil.getDocumentFilePath()+File.separator+ sourcePath.replace(entity.getFilePath(),tarfilename);
//        System.out.println(targetPath);
        UserInfo userInfo = userProvider.get();
        DocumentVersionEntity versionEntity = new DocumentVersionEntity();
        versionEntity.setCreatortime(new Date());
        versionEntity.setCreatoruserid(userInfo.getUserId());
        versionEntity.setDocid(entity.getId());
        versionEntity.setEnabledmark(1);
        versionEntity.setMainurl(targetPath);
        versionEntity.setVersion("V"+Float.parseFloat("1.0"));
        versionEntity.setFileSize(entity.getFileSize());
        DocumentVersionUtils.copeFile(scurcePath,versionEntity);
        documentVersionService.save(versionEntity);
    }


    /**
     * 文件写入
     * @param inputStream
     * @param file
     */
    public void inputStreamToFile(InputStream inputStream,File file){
        try{
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer,0,8192))!=-1){
                os.write(buffer,0,bytesRead);
            }
            os.close();
            inputStream.close();
        }catch (Exception e){
            throw new RuntimeException("文件保存异常");
        }
    }

    @Operation(summary = "编辑文件")
    @GetMapping("/editFile/{id}")
    public ActionResult editFile(HttpServletRequest request,@PathVariable("id") String id) {


        DocumentVersionEntity dv = documentVersionService.getInfo(id);
        DocumentEntity doc = documentService.getInfo(dv.getDocid());
        String ext = doc.getFileExtension();
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setSaveFilePage("saveFile?vid="+id);
//        poCtrl.setDisableCopyOnly(true);//如只是禁止拷贝文档内容到外部，请使用此属性。仅限企业版。
//        poCtrl.webOpen("E:\\doctest.docx", OpenModeType.docNormalEdit, "张三");
//        //webOpen的第一个参数支持能够输出下载文件的Url相对地址或者文件在服务器上的磁盘路径两种方式
//        //查看详细，请在本站搜索“PageOffice属性或方法中涉及到的URL路径或磁盘路径的说明”
        if(ext.toLowerCase().indexOf("doc")>-1){//word文件
            poCtrl.webOpen(dv.getMainurl(), OpenModeType.docNormalEdit, "张三");
        }
        if(ext.toLowerCase().indexOf("xls")>-1){//Excel文件
            poCtrl.webOpen(dv.getMainurl(), OpenModeType.xlsNormalEdit, "张三");
        }
        if(ext.toLowerCase().indexOf("ppt")>-1){//PPt
            poCtrl.webOpen(dv.getMainurl(), OpenModeType.pptNormalEdit, "张三");
        }
        if(ext.toLowerCase().indexOf("pdf")>-1){//pdf查看
            PDFCtrl pdfCtrl = new PDFCtrl(request);
            pdfCtrl.webOpen(dv.getMainurl());
        }



        // Linux服务器添加前缀：file://
//        poCtrl.WebOpen("file://"+"/root/documents/test.docx", OpenModeType.docReadOnly, "张三");
        String htmlCode = poCtrl.getHtmlCode();
        return  ActionResult.success(htmlCode);
    }

    @RequestMapping("/editFile/saveFile")
    public void saveFile(HttpServletRequest request, HttpServletResponse response) {
        String vid = request.getParameter("vid");
        DocumentVersionEntity docver = documentVersionService.getInfo(vid);
        FileSaver fs = new FileSaver(request, response);
//        fs.saveToFile("E:\\pageoffice\\" + fs.getFileName());
        fs.saveToFile(docver.getMainurl());
        fs.close();
    }

    @Operation(summary = "定稿")
    @GetMapping("/dingGao/{vid}")
    @Parameters({@Parameter(name = "vid", description = "主键", required = true)})
    public ActionResult dingGao(@PathVariable("vid") String vid) {

        DocumentVersionEntity docver = documentVersionService.getInfo(vid);
        DocumentEntity documentEntity = documentService.getInfo(docver.getDocid());
        String url = docver.getMainurl().replaceAll("/","_").replace("\\","_");
        String[] split = url.split("_");
        String filename = split[split.length - 1];
        Float version = Float.parseFloat(docver.getVersion().replace("V", ""));
        version +=0.1f;
        //新文件版本名
        String newvstr = "V"+version+"."+documentEntity.getFileExtension();
        //文件名版本
        String vv = docver.getVersion().replace(".","");
        String oldfilev = vv+"."+documentEntity.getFileExtension();

        //创建新版本
        UserInfo userInfo = userProvider.get();
        DocumentVersionEntity versionEntity = new DocumentVersionEntity();
        versionEntity.setCreatortime(new Date());
        versionEntity.setCreatoruserid(userInfo.getUserId());
        versionEntity.setLastmodifytime(new Date());
        versionEntity.setDocid(docver.getDocid());
        versionEntity.setEnabledmark(1);
        versionEntity.setMainurl(docver.getMainurl().replace(oldfilev,newvstr));
        versionEntity.setVersion("V"+version);
//        versionEntity.setFileSize(entity.getFileSize());
        DocumentVersionUtils.copeFile(docver.getMainurl(),versionEntity);
        documentVersionService.save(versionEntity);
        documentEntity.setVersion(versionEntity.getVersion());
        documentEntity.setLastModifyTime(new Date());
        documentService.updateById(documentEntity);
        return ActionResult.success("操作成功");
    }
}
